const { XMLParser, XMLBuilder } = require("fast-xml-parser");

// 数据合成器
const DataSynthesizer = {
    xml(content, cdata) {
        let param = {};
        if (cdata) {
            param.cdataPropName = cdata;
        }
        // 拼装 回 CDATA
        const builder = new XMLBuilder(param);
        return builder.build(content);
    },
};

const DataFormatter = {
    json(body) {
        if (typeof body === "string") {
            let tmp = null;
            // 是不是key value形式的
            try {
                tmp = JSON.parse(body);
            } catch (e) {}
            return tmp || {};
        } else if (typeof body === "object") {
            return body;
        }
        return {};
    },
    urlencoded(body) {
        let tmp = null;
        if (typeof body === "string") {
            let partArr = body.split("&");
            let resultBody = {};
            for (let i = 0; i < partArr.length; i++) {
                let part = partArr[i];
                let single = part.split("=");
                if (single.length === 2) {
                    resultBody[single[0]] = decodeURIComponent(single[1]);
                }
            }
            tmp = resultBody;
        }

        return tmp || {};
    },
    //xml
    xml(body) {
        let tmp = null;
        if (typeof body === "string") {
            const parser = new XMLParser();
            try {
                tmp = parser.parse(body);
            } catch (error) {}
        }
        return tmp || {};
    },
};

module.exports = {
    DataFormatter,
    DataSynthesizer,
};
